package com.sgcc.pda.gis;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.sgcc.pda.baselibrary.utils.LogUtil;


/**
 * Gis相关功能
 *  
 *
 * @author ShiPengHao
 * @date 2018/3/12
 */
public class GisManager {
    private static final String TAG = "GisManager";
    @SuppressLint("StaticFieldLeak")
    private static GisManager singleTon;

    private Context mAppContext;
    /**
     * 远程服务连接对象
     */
    private ServiceConnection mRemoteConn;
    /**
     * 远程服务
     */
    private IGisInterface mRemoteService;

    /**
     * 远程服务绑定监听
     */
    public interface RemoteConnectCallback {
        /**
         * 绑定成功
         */
        void onConnect();
    }

    private GisManager(Context context) {
        mAppContext = context.getApplicationContext();
    }

    public static synchronized GisManager getInstance(Context context) {
        if (null == singleTon) {
            singleTon = new GisManager(context);
        }
        return singleTon;
    }

    /**
     * 绑定远程服务
     *
     * @param connectCallback 远程服务绑定监听
     */
    public void bindRemoteService(final @Nullable RemoteConnectCallback connectCallback) {
        if (null == mRemoteService) {
            if (null == mRemoteConn) {
                mRemoteConn = new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        LogUtil.i(TAG, "onServiceConnected");
                        mRemoteService = IGisInterface.Stub.asInterface(service);
                        if (null == mRemoteService) {
                            unBindRemoteService();
                        } else if (null != connectCallback) {
                            connectCallback.onConnect();
                        }
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        LogUtil.i(TAG, "onServiceDisconnected");
//                        restartRemoteService(null);
                    }
                };
            }
            mAppContext.bindService(new Intent("com.sgcc.pda.gis.AIDLService")
                    .setPackage("com.sgcc.pda.gis"), mRemoteConn, Context.BIND_AUTO_CREATE);
        } else if (mRemoteService.asBinder() != null
                && mRemoteService.asBinder().isBinderAlive()) {
            if (null != connectCallback) {
                connectCallback.onConnect();
            }
        } else {
            restartRemoteService(connectCallback);
        }
    }

    /**
     * 重启远程服务：解绑再绑定
     *
     * @param connectCallback 远程服务绑定监听
     */
    private void restartRemoteService(RemoteConnectCallback connectCallback) {
        unBindRemoteService();
        bindRemoteService(connectCallback);
    }

    /**
     * 解绑远程服务
     */
    public void unBindRemoteService() {
        if (null != mRemoteConn) {
            mAppContext.unbindService(mRemoteConn);
            mRemoteService = null;
            mRemoteConn = null;
        }
    }

    /**
     * 远程服务已绑定且运行正常
     *
     * @return 是true否则false
     */
    public boolean isRemoteServiceAvailable() {
        return mRemoteConn != null
                && mRemoteService != null
                && mRemoteService.asBinder() != null
                && mRemoteService.asBinder().isBinderAlive();
    }

    /**
     * 初始化地图  离线地图传null 或者 ""
     *
     * @param key
     */
    public void initMap(final String key) {
        if (isRemoteServiceAvailable()) {
            try {
                mRemoteService.initMap(key);
            } catch (RemoteException e) {
                LogUtil.e(TAG, "initMap: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        mRemoteService.initMap(key);
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "initMap: " + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 关闭地图功能
     */
    public void unInitMap() {
        if (isRemoteServiceAvailable()) {
            try {
                mRemoteService.unInitMap();
            } catch (RemoteException e) {
                LogUtil.e(TAG, "unInitMap: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        mRemoteService.unInitMap();
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "unInitMap: " + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 地图功能是否已经初始化
     *
     * @return 是true，否false
     */
    boolean isInit;

    public boolean isInit() {
        if (isRemoteServiceAvailable()) {
            try {
                isInit = mRemoteService.isInit();
            } catch (RemoteException e) {
                LogUtil.e(TAG, "isInit: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        isInit = mRemoteService.isInit();
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "isInit: " + e.getMessage());
                    }
                }
            });
        }
        return isInit;
    }

    /**
     * 开启定位，开启后将一直在后台定位
     */
    public void startLocate() {
        if (isRemoteServiceAvailable()) {
            try {
                mRemoteService.startLocate();
            } catch (RemoteException e) {
                LogUtil.e(TAG, "startLocate: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        mRemoteService.startLocate();
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "startLocate : " + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 停止定位服务
     */
    public void stopLocate() {
        if (isRemoteServiceAvailable()) {
            try {
                mRemoteService.stopLocate();
            } catch (RemoteException e) {
                LogUtil.e(TAG, "stopLocate: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        mRemoteService.stopLocate();
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, "stopLocate : " + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 获取一次经纬度
     *
     * @param callback 回调
     */
    public void getLocation(final LocationCallback callback) {
        if (isRemoteServiceAvailable()) {
            try {
                mRemoteService.getLocation(callback);
            } catch (RemoteException e) {
                LogUtil.e(TAG, "getLocation: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        mRemoteService.getLocation(callback);
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, " getLocation: " + e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * 获取最后有效的位置信息
     */
    String result = "";

    public String getLastValidLocation() {
        if (isRemoteServiceAvailable()) {
            try {
                result = mRemoteService.getLastValidLocation();
            } catch (RemoteException e) {
                LogUtil.e(TAG, "getLastValidLocation: " + e.getMessage());
            }
        } else {
            bindRemoteService(new RemoteConnectCallback() {
                @Override
                public void onConnect() {
                    try {
                        result = mRemoteService.getLastValidLocation();
                    } catch (RemoteException e) {
                        LogUtil.e(TAG, " getLastValidLocation: " + e.getMessage());
                    }
                }
            });
        }
        return result;
    }

}